import React from 'react'
import {connect} from 'react-redux'
import BasicInfo from 'components/basic-info'
import autoAuditService from 'containers/finance-setting/auto-audit/auto-audit.service'
import 'styles/finance-setting/auto-audit/auto-aduit-detail.scss'
import { message } from 'antd';
import { Badge, Button, Popover, Affix, Modal } from 'antd'
import SlideFrame from "components/slide-frame";
import EditAuditDetail from 'containers/finance-setting/auto-audit/edit-audit-detail'
import {messages} from "share/common";
import menuRoute from "routes/menuRoute";
import ResizeTable from 'components/resize-table'

class AutoAuditDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      ruleInfo: {},
      ruleDetailInfo: {},
      infoList: [
        {type: 'input', id: 'ruleCode', label: messages('finance-setting.key71'/*规则编码*/), isRequired: true, disabled: true},
        {type: 'input', id: 'ruleName', label: messages('finance-setting.key72'/*规则名称*/), isRequired: true},
        {type: 'input', id: 'setOfBooksName', label: messages('finance-setting.key73'/*所属帐套*/), isRequired: true, disabled:true},
        {type: 'input', id: 'priority', label: messages('finance-setting.key74'/*优先级*/), isRequired: true, disabled:true},
        {type: 'switch', id: 'enabled', label: messages('common.column.status')/*状态*/,isRequired: true}
      ],
      page: 0,
      size: 10,
      pagination: {
        total: 0
      },
      ruleDetail: [],
      columns: [
        {title: messages('finance-setting.key75'/*规则参数类型*/), dataIndex:'ruleType', render: value => this.getRuleType(value)},
        {title: messages('finance-setting.key76'/*规则参数*/), dataIndex:'ruleParameter', render: value => this.getRuleParameter(value)},
        {title: messages('finance-setting.key77'/*取值方式*/), dataIndex:'compareType', render: value => this.getCompareType(value)},
        {title: messages('finance-setting.key78'/*取值*/), dataIndex:'itemValue', render: (value,record) => this.getItemValue(value,record)},
        {title: messages('common.column.status')/*状态*/, dataIndex:'enabled', render: value => { return value ? <Badge text={messages('common.status.enable')/*启用*/} status={'success'}/> : <Badge text={messages('common.status.disable')/*禁用*/} status={'error'}/>}},
        {title: messages('common.operation')/*操作*/, dataIndex:'operate', render: (value,record) => <a onClick={e => this.editDetailRule(e,record)} disabled={!this.props.tenantMode}>{messages('common.edit')/*编辑*/}</a> },
      ],
      upDateBasic: false,
      upLoad: false,
      tableLoading: false,
      slideShow: false,
      title: '',
      ruleId: '',
      mappingTable: {},
      helpListShow: false,
      autoAudit: menuRoute.getRouteItem('auto-audit')
    };
  }

  componentWillMount() {
    this.setState({
      ruleId: this.props.location.state.ruleInfo.id,
    },() => {
      autoAuditService.mapDetail().then(res => {
        this.setState({
          mappingTable: res.data
        },() => {
          this.getList();
        });
      }).catch(() => {
        message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
      });
    });
  }

  getList = () => {
    const {page, size, ruleId} = this.state;
    let params = {
      ruleId: ruleId,
      page: page,
      size: size
    };
    this.setState({
      tableLoading: true,
      upLoad: true
    });
    Promise.all([
      autoAuditService.getRuleDetailTable(params),
      autoAuditService.getRuleInfo(ruleId)
    ]).then(ruleRes => {
      this.setState({
        ruleDetail: ruleRes[0].data,
        tableLoading: false,
        upDateBasic: true,
        upLoad: false,
        ruleInfo: ruleRes[1].data,
        pagination: {
          total: Number(ruleRes[0].headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(() => {
      message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
    });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  //基本信息编辑保存
  handleEdit = (params) => {
    const { ruleInfo } = this.state;
    let ruleParams = JSON.parse(JSON.stringify(ruleInfo));
    ruleParams.ruleName = params.ruleName;
    ruleParams.enabled = params.enabled;
    if(params.ruleName.length > 50){
      message.error(messages('finance-setting.key80'/*规则名称最多不超过50个字符*/));
      return -1;
    };
    delete ruleParams.companyDTOs;
    this.setState({ upLoad: true });
    autoAuditService.infoUpdate(ruleParams).then(() => {
      this.setState({
        ruleInfo: ruleParams,
        upLoad: false,
        upDateBasic: true
      });
    }).catch(() => {
      this.setState({upLoad:false});
      message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
    });
  };

  //规则详情编辑
  editDetailRule = (e,record) => {
    e.stopPropagation();
    this.setState({
      ruleDetailInfo:record,
      title: messages('finance-setting.key81'/*编辑规则*/)
    },() => {
      this.setState({slideShow:true});
    });
  };

  //渲染规则参数类型
  getRuleType = (value) => {
    const {mappingTable} = this.state;
    let result = '';
    mappingTable.autoAuditRelative.map(item => {
      item.value === `${value}` && (result = item.text);
    });
    return result;
  };

  //渲染规则参数
  getRuleParameter = (value) => {
    const {mappingTable} = this.state;
    let result = '';
    mappingTable.autoAuditType.map(item => {
      item.value === `${value}` && (result = item.text);
    });
    return result;
  };

  //渲染取值方式
  getCompareType = (value) => {
    switch (value){
      case 'contain':
        return messages('finance-setting.key82'/*包含*/);
        break;
      case 'exclude':
        return messages('finance-setting.key83'/*排除*/);
        break;
      default:
        return '-'
    } ;
  };

  //渲染取值
  getItemValue = (value,record) => {
    switch (record.paramValueType) {
      case 1002:
        return <Popover content={`${value.showValue[0].showValue}-${value.showValue[1].showValue}`} placement="topLeft"><span>{value.showValue[0].showValue}-{value.showValue[1].showValue}</span></Popover>;
        break;
      default:
        let showString = '';
        let length = value.showValue.length;
        value.showValue.map((item,index) => {
          index === length - 1 ? (showString += item.showValue) : (showString += `${item.showValue},`);
        });
        return <Popover content={showString} placement="topLeft"><span>{showString}</span></Popover>;
        break;
    }
  };

  //新建规则
  newDetailRule = () => {
    this.setState({
      title: messages('finance-setting.key84'/*新建规则*/),
      ruleDetailInfo: null
    },() => {
      this.setState({slideShow: true});
    })
  };

  goBack = () => {
    this.context.router.push(this.state.autoAudit.url);
  };

  render(){
    const { ruleInfo, infoList, ruleDetail, upDateBasic, upLoad, columns, pagination, tableLoading, slideShow, title,
      ruleDetailInfo, ruleId, helpListShow } = this.state;
    return(
      <div className="auto-audit-detail">
        <BasicInfo infoList={infoList}
                   isHideEditBtn={!this.props.tenantMode}
                   infoData={ruleInfo}
                   updateHandle={this.handleEdit}
                   updateState={upDateBasic}
                   loading={upLoad}/>
        <div className="auto-audit-detail-title">{messages('finance-setting.key85'/*规则明细*/)}<span>{messages('finance-setting.key86'/*共搜索到*/)}<span className='color'>{pagination.total}</span>{messages('finance-setting.key87'/*条数据*/)}</span></div>
        <div style={{marginBottom:'10px'}}>
          <Button type="primary" onClick={this.newDetailRule} disabled={!this.props.tenantMode}>{messages('common.create')/*新建*/}</Button>
          <Button onClick={() => {
            this.setState({helpListShow: true});
          }} style={{marginLeft: '10px'}}>{messages('finance-setting.key189')/*查看帮助*/}</Button>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={ruleDetail}
          pagination={pagination}
          bordered
          loading={tableLoading}/>
        <SlideFrame show={slideShow}
                    title={title}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      ruleDetailInfo,
                      ruleId,
                      slideShow
                    }}
                    content={EditAuditDetail}
                    onClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.getList();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.getList();
                    }}/>
        <Modal visible={helpListShow}
               className={'help-modal'}
               width={900}
               footer={null}
               title={messages('finance-setting.key190')/*帮助*/}
               onCancel={() => {this.setState({helpListShow: false})}}>
          <div className='help-header-title'><span>{messages('finance-setting.key206')/*规则校验逻辑*/}</span></div>
          <div style={{margin: '5px 0px'}}>{messages('finance-setting.key193')/*（1）同一条规则详情内的取值间为或；*/}</div>
          <div style={{margin: '5px 0px'}}>{messages('finance-setting.key194')/*（2）不同的规则详情间取交；*/}</div>
        </Modal>
        <Affix offsetBottom={0} className="bottom-bar"><Button className="back-btn" onClick={this.goBack}>{messages('common.back')/*返回*/}</Button></Affix>
      </div>
    )
  }
}

AutoAuditDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(AutoAuditDetail);
